package cn.edu.csust.coursecard.interceptor;

import cn.edu.csust.coursecard.common.CodeEnum;
import cn.edu.csust.coursecard.common.RedisKeyEnum;
import cn.edu.csust.coursecard.exception.BaseException;
import cn.edu.csust.coursecard.utils.RedisUtil;
import cn.edu.csust.coursecard.utils.TokenUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zsw
 * @date 2019/11/18 22:35
 * @version 1.0
 * @author yaoyaoyao
 * @date 2022/08/11
 * @version 2.0
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    TokenUtils tokenUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String inputToken = request.getHeader(tokenUtils.getTokenName());
        if (inputToken == null || "".equals(inputToken.trim())) {
            throw new BaseException(CodeEnum.REQUEST_FAILED.getCode(),"尚未登录！");
        }
        Integer id = tokenUtils.getIdFromToken(inputToken);
        Boolean isAdmin = tokenUtils.getIsAdminFromToken(inputToken);
        if(!isAdmin){
            String nowToken = (String) redisUtil.get(RedisKeyEnum.USER_TOKEN_PREFIX + id);
            if(!inputToken.equals(nowToken)){
                throw new BaseException(CodeEnum.REQUEST_FAILED.getCode(),"验证失败，请重新登录！");
            }
            Object stuNum = redisUtil.get(RedisKeyEnum.USER_STUNUM_PREFIX+id);
            redisUtil.set(RedisKeyEnum.USER_TOKEN_PREFIX + id,nowToken, RedisKeyEnum.TOKEN_EXPIRE);
            request.setAttribute("userId",id);
            request.setAttribute("stuId",stuNum);
        }else {
            request.setAttribute("admin",true);
        }
        return true;
    }
}
